// pages/booking/confirm.js
Page({
  data: {
    venueId: null,
    venueInfo: {},
    date: '',
    timeSlot: {},
    timeSlots: [],
    roomId: null,
    roomName: '',
    peopleCount: 2,
    totalPrice: 0,
    remark: '',
    loading: true
  },

  onLoad: function(options) {
    // 获取参数
    if (options.venueId && options.date && options.timeSlotId) {
      this.setData({
        venueId: options.venueId,
        date: options.date,
        roomId: options.roomId || null,
        roomName: options.roomName || ''
      });
      
      // 加载场馆信息
      this.loadVenueInfo();
      
      // 加载时间段信息
      this.loadTimeSlotInfo(options.timeSlotId);
      
      // 检查登录状态
      this.checkLoginStatus();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 检查登录状态
  checkLoginStatus: function() {
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.showModal({
        title: '提示',
        content: '预约需要登录，是否前往登录？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/user/login'
            });
          } else {
            wx.navigateBack();
          }
        }
      });
    }
  },
  
  // 加载场馆信息
  loadVenueInfo: function() {
    // 模拟数据，实际项目中应该从服务器获取
    const venueDetails = {
      1: {
        id: 1,
        name: '欢乐棋牌室',
        address: '北京市海淀区中关村大街1号',
        type: '棋牌室',
        imageUrl: '/images/venue/venue1.jpg'
      },
      2: {
        id: 2,
        name: '星牌台球俱乐部',
        address: '北京市海淀区中关村大街2号',
        type: '台球室',
        imageUrl: '/images/venue/venue2.jpg'
      },
      3: {
        id: 3,
        name: '麦乐迪KTV',
        address: '北京市海淀区中关村大街3号',
        type: 'KTV',
        imageUrl: '/images/venue/venue3.jpg'
      },
      4: {
        id: 4,
        name: '聚友棋牌',
        address: '北京市朝阳区建国路5号',
        type: '棋牌室',
        imageUrl: '/images/venue/venue4.jpg'
      },
      5: {
        id: 5,
        name: '乐动台球',
        address: '北京市朝阳区建国路6号',
        type: '台球室',
        imageUrl: '/images/venue/venue5.jpg'
      },
      6: {
        id: 6,
        name: '好声音KTV',
        address: '北京市朝阳区建国路7号',
        type: 'KTV',
        imageUrl: '/images/venue/venue6.jpg'
      }
    };
    
    const venueInfo = venueDetails[this.data.venueId];
    
    if (venueInfo) {
      this.setData({
        venueInfo: venueInfo
      });
      
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: '预约确认'
      });
    } else {
      wx.showToast({
        title: '未找到场馆信息',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 加载时间段信息
  loadTimeSlotInfo: function(timeSlotIds) {
    // 模拟数据，实际项目中应该从服务器获取
    const allTimeSlots = [
      { id: 1, time: '10:00-11:00', price: '30元/小时', priceValue: 30 },
      { id: 2, time: '11:00-12:00', price: '30元/小时', priceValue: 30 },
      { id: 3, time: '12:00-13:00', price: '30元/小时', priceValue: 30 },
      { id: 4, time: '13:00-14:00', price: '30元/小时', priceValue: 30 },
      { id: 5, time: '14:00-15:00', price: '30元/小时', priceValue: 30 },
      { id: 6, time: '15:00-16:00', price: '30元/小时', priceValue: 30 },
      { id: 7, time: '16:00-17:00', price: '30元/小时', priceValue: 30 },
      { id: 8, time: '17:00-18:00', price: '40元/小时', priceValue: 40 },
      { id: 9, time: '18:00-19:00', price: '40元/小时', priceValue: 40 },
      { id: 10, time: '19:00-20:00', price: '40元/小时', priceValue: 40 },
      { id: 11, time: '20:00-21:00', price: '40元/小时', priceValue: 40 },
      { id: 12, time: '21:00-22:00', price: '40元/小时', priceValue: 40 }
    ];
    
    // 解析时间段ID列表
    const idList = timeSlotIds.split(',').map(id => parseInt(id));
    
    // 获取选中的时间段
    const selectedTimeSlots = allTimeSlots.filter(item => idList.includes(item.id));
    
    if (selectedTimeSlots.length > 0) {
      // 按ID排序
      selectedTimeSlots.sort((a, b) => a.id - b.id);
      
      // 计算总价
      const totalPriceValue = selectedTimeSlots.reduce((sum, slot) => sum + slot.priceValue, 0);
      
      // 生成时间段显示文本
      let timeSlotDisplay;
      if (selectedTimeSlots.length === 1) {
        timeSlotDisplay = selectedTimeSlots[0];
      } else {
        // 对于多个时间段，合并显示
        const firstSlot = selectedTimeSlots[0];
        const lastSlot = selectedTimeSlots[selectedTimeSlots.length - 1];
        const timeRange = `${firstSlot.time.split('-')[0]}-${lastSlot.time.split('-')[1]}`;
        const priceText = selectedTimeSlots[0].price.replace(/元\/小时/, '元') + ` x ${selectedTimeSlots.length}小时`;
        
        timeSlotDisplay = {
          id: firstSlot.id,
          time: timeRange,
          price: priceText,
          priceValue: totalPriceValue
        };
      }
      
      this.setData({
        timeSlot: timeSlotDisplay,
        timeSlots: selectedTimeSlots,
        totalPrice: totalPriceValue * this.data.peopleCount,
        loading: false
      });
    } else {
      wx.showToast({
        title: '未找到时间段信息',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 修改人数
  onChangePeopleCount: function(e) {
    const type = e.currentTarget.dataset.type;
    let count = this.data.peopleCount;
    
    if (type === 'minus' && count > 1) {
      count--;
    } else if (type === 'plus' && count < 10) {
      count++;
    }
    
    this.setData({
      peopleCount: count,
      totalPrice: this.data.timeSlot.priceValue * count
    });
  },
  
  // 输入备注
  onInputRemark: function(e) {
    this.setData({
      remark: e.detail.value
    });
  },
  
  // 提交预约
  onTapSubmit: function() {
    // 检查登录状态
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.navigateTo({
        url: '/pages/user/login'
      });
      return;
    }
    
    // 显示加载中
    wx.showLoading({
      title: '提交中...'
    });
    
    // 模拟提交预约请求
    setTimeout(() => {
      wx.hideLoading();
      
      // 模拟成功响应
      wx.showToast({
        title: '预约成功',
        icon: 'success'
      });
      
      // 修改：使用redirectTo而不是switchTab，确保能正确跳转到预约列表页
      setTimeout(() => {
        try {
          // 先尝试使用redirectTo
          wx.redirectTo({
            url: '/pages/booking/index',
            fail: function(err) {
              console.error('redirectTo失败:', err);
              // 如果redirectTo失败，尝试使用switchTab
              wx.switchTab({
                url: '/pages/booking/index',
                fail: function(err2) {
                  console.error('switchTab也失败:', err2);
                  // 如果都失败，尝试使用navigateTo
                  wx.navigateTo({
                    url: '/pages/booking/index'
                  });
                }
              });
            }
          });
        } catch (e) {
          console.error('跳转异常:', e);
          // 出现异常时，使用最基本的navigateBack
          wx.navigateBack();
        }
      }, 1500);
    }, 1500);
  },
  
  // 邀请好友
  onTapInviteFriends: function() {
    // 检查登录状态
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.navigateTo({
        url: '/pages/user/login'
      });
      return;
    }
    
    // 跳转到好友列表页
    wx.navigateTo({
      url: '/pages/user/friends?from=booking'
    });
  },
  
  // 创建组队
  onTapCreateTeam: function() {
    // 检查登录状态
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.navigateTo({
        url: '/pages/user/login'
      });
      return;
    }
    
    // 跳转到创建组队页面
    wx.navigateTo({
      url: `/pages/team/create?venueId=${this.data.venueId}&date=${this.data.date}&timeSlotId=${this.data.timeSlot.id}`
    });
  }
})